package com.fz.us.admin.company.service.impl;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.search.Search;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PagePaging;
import com.fz.us.admin.base.bean.search.result.SearchResult;
import com.fz.us.admin.base.bean.search.result.SearchResultList;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.service.impl.BaseServiceImpl;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.dao.BaseFlowDao;
import com.fz.us.admin.base.dao.BaseDao;


import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.files.WorkflowUtils;
import com.fz.us.admin.company.service.*;
import com.fz.us.admin.company.service.BaseFlowService;
import com.fz.us.admin.company.service.CommonConfigService;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.JointlySignService;
import com.fz.us.admin.company.service.ProcessBriefService;
import com.fz.us.admin.company.service.StepBriefService;
import com.fz.us.admin.company.service.StepConService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.TaskFlowService;
import com.fz.us.admin.company.service.TaskRecordService;


import com.google.common.collect.Lists;
import com.google.common.collect.Sets;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


import java.util.*;


/**
 * Service实现类 - 
 * ============================================================================
  * 版权所有 2013 。
 * ----------------------------------------------------------------------------
 * 
 * @author 
 *
 * @version 0.1 2013-01-06
 */
@Service
public abstract class BaseFlowServiceImpl<T extends BaseFlowEntity, PK extends String>  extends BaseServiceImpl<T,PK> implements BaseFlowService<T,PK>{

    @Autowired
    protected TaskRecordService taskRecordService;
    //add by zhucx
    @Autowired
    protected TaskEntityService taskEntityService;
    //add by zhucx
    @Autowired
    protected TaskFlowService taskFlowService;
    //add by zhucx
    @Autowired
    protected ProcessBriefService processBriefService;
    //add by zhucx
    @Autowired
    protected StepBriefService stepBriefService;
    //add by zhucx
    @Autowired
    protected CommonConfigService commonConfigService;
    //add by zhucx
    @Autowired
    protected StepConService stepConService;
    //add by zhucx
    @Autowired
    protected JointlySignService jointlySignService;
    //add by zhucx
    @Autowired
    protected DutyService dutyService;
    @Autowired
    protected UserService userService;

    public abstract BaseFlowDao<T,PK> getBaseFlowDao();

    @Override
    public BaseDao<T, PK> getBaseDao() {
        return getBaseFlowDao();
    }

    @Override
    //add by zhucx
    public PK save(T entity, String entityName) {
        User user = userService.getLoginInfo();
        entity.setProcessState(FlowEnum.ProcessState.Draft);
        PK pk =  save(entity);
        TaskEntity taskEntity = taskEntityService.get(pk);
        if(taskEntity == null){
            taskEntity = new TaskEntity();
            taskEntity.setCreater(user);
            taskEntity.setKeyId(pk);
            taskEntity.setStepNo(1);
            taskEntity.setEntityName(entityName);
            taskEntity.setProcessState(FlowEnum.ProcessState.Draft);
            taskEntityService.save(taskEntity);
        }
        return pk;
    }

    @Override
    //add by zhucx New
    public PK commit(T entity, String entityName, User user, String next, User editor) {
        PK pk = save(entity);
        //任务实体
        TaskEntity taskEntity = taskEntityService.get(pk);
        //已办标志
        int type = 1;
        Set<User> prevUsers = new HashSet<User>();
        Set<User> editors = new HashSet<User>();
        prevUsers.add(user);
        if(editor!= null){
            editors.add(editor);
        }
        if(taskEntity == null){
            taskEntity = new TaskEntity();
            taskEntity.setCreater(user);
            taskEntity.setKeyId(pk);
            taskEntity.setEntityName(entityName);
            if(StringUtils.equals(next, "1")){
                taskEntity.setStepNo(2);
                entity.setProcessState(FlowEnum.ProcessState.Running);
                taskEntity.setProcessState(FlowEnum.ProcessState.Running);
            }else{
                type = 2;
                taskEntity.setStepNo(1);
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                taskEntity.setProcessState(FlowEnum.ProcessState.Finished);
            }
            taskEntity.setPrevUsers(prevUsers);
            taskEntity.setEditors(editors);
            taskEntityService.save(taskEntity);
            update(entity);
        }
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setType(FlowEnum.TaskFlowType.create);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        return pk;
    }


    @Override
    //add by zhucx
    public PK commit(T entity, String entityName, Duty duty) {
        User user = userService.getLoginInfo();
        PK pk = save(entity);
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(pk);
        //已办标志
        int type = 1;
        //下一步步骤简要表对象
        StepBrief stepBrief = null;
        if(taskEntity == null){
            taskEntity = new TaskEntity();
            taskEntity.setCreater(user);
            taskEntity.setKeyId(pk);
            ProcessBrief processBrief = processBriefService.getInfoByTableKey(entityName);
            StepBrief firstStepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
            if(firstStepBrief.getRouteType() != 2){ //一般路由
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, firstStepBrief.getNextStepNo());
            }else{ //条件路由
                Map<String, Object> parmas = new HashMap<String, Object>();
                parmas.put("stepBrief", firstStepBrief);
                parmas.put("state", BaseEnumManager.StateEnum.Enable);
                List<StepCon> stepConList = stepConService.getList(parmas);
                for(StepCon stepCon:stepConList){
                    if(calStepCon(stepCon.getFormulaField(),stepCon.getFormulaFlag(),stepCon.getFormulaVal(),pk,entityName) == true){
                        stepBrief = stepBriefService.getInfoByStepNo(processBrief, stepCon.getStepNo());
                        break;
                    }
                }
            }
            Set<User> editors = new HashSet<User>();
            Set<User> readers = new HashSet<User>();
            if(stepBrief == null){//直接归档
                type = 2;
                taskEntity.setStepNo(1);
                taskEntity.setProcessState(FlowEnum.ProcessState.Finished);
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                List<Duty> docDutyList = Lists.newArrayList();
                if(processBrief.getDocConfig() != null){
                    docDutyList = commonConfigService.findDutyByConfig(pk,entityName, processBrief.getDocConfig().getId());
                }
                List<Duty> editDutyList = Lists.newArrayList();
                if(processBrief.getEditConfig() != null){
                    editDutyList = commonConfigService.findDutyByConfig(pk,entityName, processBrief.getEditConfig().getId());
                }
                List<Duty> readDutyList = Lists.newArrayList();
                if(processBrief.getReadConfig() != null){
                    readDutyList = commonConfigService.findDutyByConfig(pk, entityName, processBrief.getReadConfig().getId());
                }
                docDutyList.addAll(editDutyList);
                docDutyList.addAll(readDutyList);
                for(Duty readDuty: docDutyList){
                    if(readDuty.getUser() != null){
                        readers.add(readDuty.getUser());
                    }
                }
                for(Duty editDuty: editDutyList){
                    if(editDuty.getUser() != null){
                        editors.add(editDuty.getUser());
                    }
                }
            }else{//流转
                taskEntity.setStepNo(stepBrief.getStepNo());
                taskEntity.setProcessState(FlowEnum.ProcessState.Running);
                entity.setProcessState(FlowEnum.ProcessState.Running);
                List<Duty> editDutyList = Lists.newArrayList();
                if(stepBrief.getCommonConfig() != null){
                    editDutyList = commonConfigService.findDutyByConfig(pk, entityName, stepBrief.getCommonConfig().getId());
                }
                List<Duty> docDutyList = Lists.newArrayList();
                if(processBrief.getDocConfig() != null){
                    docDutyList = commonConfigService.findDutyByConfig(pk, entityName, processBrief.getDocConfig().getId());
                }
                List<User> specialUsersList = stepBriefService.findSpecailByUser(stepBrief, duty);
                for(Duty editDuty: editDutyList){
                   if(editDuty.getUser() != null){
                       editors.add(editDuty.getUser());
                   }
                }
                editors.addAll(specialUsersList);
                docDutyList.addAll(editDutyList);
                for(Duty readDuty: docDutyList){
                    if(readDuty.getUser() != null){
                        readers.add(readDuty.getUser());
                    }
                }
                readers.addAll(specialUsersList);
            }
            readers.add(user);
            Set<User> prevUsers = Sets.newHashSet();
            prevUsers.add(user);
            taskEntity.setPrevUsers(prevUsers);
            taskEntity.setEntityName(entityName);
            taskEntity.setReaders(readers);
            taskEntity.setEditors(editors);
            taskEntityService.save(taskEntity);
            update(entity);
        }

        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setDuty(duty);
        taskFlow.setType(FlowEnum.TaskFlowType.create);
        taskFlow.setStepBrief(stepBrief);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        return pk;
    }

    @Override
    public void approve(T entity, Duty duty, String comment) {
        User user = userService.getLoginInfo();
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        //流程简要
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
        //当前步骤
        StepBrief nowStepBrief = stepBriefService.getInfoByStepNo(processBrief, taskEntity.getStepNo());
        //下一步骤
        StepBrief stepBrief = null;
        //会签删除当前用户的人员
        Set<User> delUsersSet = Sets.newHashSet();
        //不是会签
        if(nowStepBrief.isJointlySing() == false){
            if(nowStepBrief.getRouteType() != 2){ //一般路由
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, nowStepBrief.getNextStepNo());
            }else{ //条件路由
                Map<String, Object> parmas = new HashMap<String, Object>();
                parmas.put("stepBrief", nowStepBrief);
                parmas.put("state", BaseEnumManager.StateEnum.Enable);
                List<StepCon> stepConList = stepConService.getList(parmas);
                for(StepCon stepCon:stepConList){
                    if(calStepCon(stepCon.getFormulaField(),stepCon.getFormulaFlag(),stepCon.getFormulaVal(),entity.getId(),taskEntity.getEntityName()) == true){
                        stepBrief = stepBriefService.getInfoByStepNo(processBrief, stepCon.getStepNo());
                        break;
                    }
                }
            }
        }else{ //会签
            Map<String, Object> params = new HashMap();
            params.put("taskEntity", taskEntity);
            params.put("stepBrief", nowStepBrief);
            params.put("state", BaseEnumManager.StateEnum.Enable);
            Set<JointlySign> jointlySignSet = Sets.newHashSet();
            jointlySignSet.addAll(jointlySignService.getList(params)) ;
            if(jointlySignSet.size() == 0){ //没有会签信息数据，说明是第一次生成
                List<Duty> editDutyList = Lists.newArrayList();
                Set<User> editors = new HashSet();
                if(nowStepBrief.getCommonConfig() != null){
                    editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), nowStepBrief.getCommonConfig().getId());
                }
                List<User> specialUsersList = stepBriefService.findSpecailByUser(nowStepBrief, duty);
                for(Duty editDuty: editDutyList){
                    if(editDuty.getUser() != null){
                        editors.add(editDuty.getUser());
                    }
                }
                editors.addAll(specialUsersList);
                for(User user1:editors){
                    JointlySign jointlySign = new JointlySign();
                    jointlySign.setTaskEntity(taskEntity);
                    jointlySign.setStepBrief(nowStepBrief);
                    jointlySign.setUser(user1);
                    if(user == user1){
                        jointlySign.setFinish(true);
                    }else{
                        jointlySign.setFinish(false);
                    }
                    jointlySignService.save(jointlySign);
                }
                delUsersSet.add(user);
                stepBrief = nowStepBrief;
            }else{//有会签数据，要更新完成状态
                for(JointlySign jointlySign:jointlySignSet){
                    if(jointlySign.getUser() == user){
                        jointlySign.setFinish(true);
                        jointlySignService.update(jointlySign);
                        break;
                    }
                }
                //查找做完的会签
                Map<String, Object> params2 = new HashMap();
                params2.put("taskEntity", taskEntity);
                params2.put("stepBrief", nowStepBrief);
                params2.put("state", BaseEnumManager.StateEnum.Enable);
                params2.put("finish", true);
                Set<JointlySign>  jointlySignFinishSet = Sets.newHashSet();
                jointlySignFinishSet.addAll(jointlySignService.getList(params2)) ;
                for(JointlySign jointlySign:jointlySignFinishSet){
                    delUsersSet.add(jointlySign.getUser());
                }
                //数量一样，表示都会签完成，可以走下一步，否则还是当前步骤
                if(jointlySignFinishSet.size() == jointlySignSet.size()){
                    if(nowStepBrief.getRouteType() != 2) { //一般路由
                        stepBrief = stepBriefService.getInfoByStepNo(processBrief, nowStepBrief.getNextStepNo());
                    }else{ //条件路由
                        Map<String, Object> parmas = new HashMap<String, Object>();
                        parmas.put("stepBrief", nowStepBrief);
                        parmas.put("state", BaseEnumManager.StateEnum.Enable);
                        List<StepCon> stepConList = stepConService.getList(parmas);
                        for(StepCon stepCon:stepConList){
                            if(calStepCon(stepCon.getFormulaField(),stepCon.getFormulaFlag(),stepCon.getFormulaVal(),entity.getId(),taskEntity.getEntityName()) == true){
                                stepBrief = stepBriefService.getInfoByStepNo(processBrief, stepCon.getStepNo());
                                break;
                            }
                        }
                    }
                }else{
                    stepBrief = nowStepBrief;
                }
            }
        }


        Set<User> editors = new HashSet<User>();
        Set<User> readers = new HashSet<User>();
        //已办标志
        int type = 1;
        if(stepBrief == null){//直接归档
            type = 2;
            taskEntity.setStepNo(nowStepBrief.getNextStepNo());
            taskEntity.setProcessState(FlowEnum.ProcessState.Finished);
            entity.setProcessState(FlowEnum.ProcessState.Finished);
            List<Duty> docDutyList = Lists.newArrayList();
            if(processBrief.getDocConfig() != null){
                docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
            }
            List<Duty> editDutyList = Lists.newArrayList();
            if(processBrief.getEditConfig() != null){
                editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getEditConfig().getId());
            }
            List<Duty> readDutyList = Lists.newArrayList();
            if(processBrief.getReadConfig() != null){
                readDutyList = commonConfigService.findDutyByConfig(entity.getId(), taskEntity.getEntityName(), processBrief.getReadConfig().getId());
            }
            docDutyList.addAll(editDutyList);
            docDutyList.addAll(readDutyList);
            for(Duty readDuty: docDutyList){
                if(readDuty.getUser() != null){
                    readers.add(userService.get(readDuty.getUser().getId()));
                }
            }
            for(Duty editDuty: editDutyList){
                if(editDuty.getUser() != null){
                    editors.add(userService.get(editDuty.getUser().getId()));
                }
            }
        }else{//流转


            /*
            List<TaskFlow> taskFlowList = taskFlowService.getTaskFlowByCreatetime();
            if(taskFlowList.size()>0){
                TaskFlow taskFlow = taskFlowList.get(taskFlowList.size()-1);
                prevUsers.add(taskFlow.getUsers());
            }*/

            taskEntity.setStepNo(stepBrief.getStepNo());
            taskEntity.setProcessState(FlowEnum.ProcessState.Running);
            entity.setProcessState(FlowEnum.ProcessState.Running);
            List<Duty> editDutyList = Lists.newArrayList();
            if(stepBrief.getCommonConfig() != null){
                editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), stepBrief.getCommonConfig().getId());
            }
            List<Duty> docDutyList = Lists.newArrayList();
            if(processBrief.getDocConfig() != null){
                docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
            }
            List<User> specialUsersList = stepBriefService.findSpecailByUser(stepBrief, duty);
            for(Duty editDuty: editDutyList){
                if(editDuty.getUser() != null){
                    editors.add(editDuty.getUser());
                }
            }
            editors.addAll(specialUsersList);
            //会签时，要删除会签过的人
            if(stepBrief == nowStepBrief){
                editors.removeAll(delUsersSet);
            }
            docDutyList.addAll(editDutyList);
            for(Duty readDuty: docDutyList){
                if(readDuty.getUser() != null){
                    readers.add(readDuty.getUser());
                }
            }
            readers.addAll(specialUsersList);
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnumManager.StateEnum.Enable);
        params.put("taskEntity", taskEntity);
        List<TaskFlow> taskFlowList1 = taskFlowService.getList(params);
        for(TaskFlow taskFlow:taskFlowList1){
            readers.add(taskFlow.getUser());
        }
        readers.add(user);
        Set<User> prevUsers = Sets.newHashSet();
        prevUsers.add(user);
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setReaders(readers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setDuty(duty);
        taskFlow.setComment(comment);
        if(StringUtils.isNotEmpty(comment)){
            taskFlow.setType(FlowEnum.TaskFlowType.approve);
        }else{
            taskFlow.setType(FlowEnum.TaskFlowType.reSubmit);
        }
        taskFlow.setStepBrief(stepBrief);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        if(type == 2){
            for(TaskRecord taskRecord:taskRecords){
                taskRecord.setType(2);
                taskRecordService.update(taskRecord);
            }
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }

    }

    //add bu zhucx New
    @Override
    public void approve(T entity, User user, String comment, String next, User editor) {
        //已办标志
        int type = 1;
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        Set<User> prevUsers = new HashSet<User>();
        Set<User> editors = new HashSet<User>();
        prevUsers.add(user);
        if(editor != null){
            editors.add(editor);
        }
        if(StringUtils.equals(next, "1")){
            taskEntity.setStepNo(taskEntity.getStepNo()+1);
            taskEntity.setProcessState(FlowEnum.ProcessState.Running);
            entity.setProcessState(FlowEnum.ProcessState.Running);
        }else{
            type = 2;
            entity.setProcessState(FlowEnum.ProcessState.Finished);
            taskEntity.setProcessState(FlowEnum.ProcessState.Finished);
        }
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setComment(comment);
        if(StringUtils.isNotEmpty(comment)){
            taskFlow.setType(FlowEnum.TaskFlowType.approve);
        }else{
            taskFlow.setType(FlowEnum.TaskFlowType.reSubmit);
        }

        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        if(type == 2){
            for(TaskRecord taskRecord:taskRecords){
                taskRecord.setType(2);
                taskRecordService.update(taskRecord);
            }
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }


    @Override
    public void back(T entity, Duty duty, String comment) {
        User user = userService.getLoginInfo();
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
        StepBrief nowStepBrief = stepBriefService.getInfoByStepNo(processBrief, taskEntity.getStepNo());
        int backStepNo = nowStepBrief.getBackStepNo() == 0?1:nowStepBrief.getBackStepNo();
        StepBrief  stepBrief = stepBriefService.getInfoByStepNo(processBrief, backStepNo);
        Set<User> editors = new HashSet<User>();
        Set<User> readers = new HashSet<User>();
        //已办标志
        int type = 1;
        if(stepBrief == null){//到第一步
           stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
        }

        /*
        List<TaskFlow> taskFlowList = taskFlowService.getTaskFlowByCreatetime();
        if(taskFlowList.size()>0){
            TaskFlow taskFlow = taskFlowList.get(taskFlowList.size()-1);
            prevUsers.add(taskFlow.getUsers());
        }*/

        taskEntity.setStepNo(stepBrief.getStepNo());
        taskEntity.setProcessState(FlowEnum.ProcessState.Backed);
        entity.setProcessState(FlowEnum.ProcessState.Backed);
        List<Duty> editDutyList = Lists.newArrayList();
        if(stepBrief.getStepNo() == 1){
           editDutyList.addAll(dutyService.getDutys(entity.getCreater()));
        }else{
            if(stepBrief.getCommonConfig() != null){
                editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), stepBrief.getCommonConfig().getId());
            }
        }

        List<Duty> docDutyList = Lists.newArrayList();
        if(processBrief.getDocConfig() != null){
            docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
        }
        for(Duty editDuty: editDutyList){
            if(editDuty.getUser() != null){
                editors.add(userService.get(editDuty.getUser().getId()));
            }
        }
        List<User> specialUsersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(stepBrief.getSpecialType())){
            List<TaskFlow> taskFlowList = taskFlowService.getInfoByTaskStepBrief(taskEntity, stepBrief);
            for(TaskFlow taskFlow: taskFlowList){
                specialUsersList.addAll(stepBriefService.findSpecailByUser(stepBrief, taskFlow.getDuty()));
            }
        }
        readers.addAll(specialUsersList);
        if(stepBrief.getStepNo() != 1){
            editors.addAll(specialUsersList);
        }
        docDutyList.addAll(editDutyList);
        for(Duty readDuty: docDutyList){
            if(readDuty.getUser() != null){
                readers.add(userService.get(readDuty.getUser().getId()));
            }
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnumManager.StateEnum.Enable);
        params.put("taskEntity", taskEntity);
        List<TaskFlow> taskFlowList1 = taskFlowService.getList(params);
        for(TaskFlow taskFlow:taskFlowList1){
            readers.add(taskFlow.getUser());
        }
        readers.add(user);
        Set<User> prevUsers = Sets.newHashSet();
        prevUsers.add(user);
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setReaders(readers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setDuty(duty);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.back);
        taskFlow.setStepBrief(stepBrief);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        //删除所有对应会签信息，重新开始会签
        Map<String, Object> params2 = new HashMap();
        params2.put("taskEntity", taskEntity);
        params2.put("state", BaseEnumManager.StateEnum.Enable);
        List<JointlySign> jointlySignList = jointlySignService.getList(params2);
        for(JointlySign jointlySign:jointlySignList){
            jointlySign.setState(BaseEnumManager.StateEnum.History);
            jointlySignService.update(jointlySign);
        }
    }

    @Override
    public void back(T entity,  String comment, int stepNo, User editor) {
        User user = userService.getLoginInfo();
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        Set<User> prevUsers = Sets.newHashSet();
        Set<User> editors = new HashSet<User>();
        prevUsers.add(user);
        editors.add(editor);
        taskEntity.setStepNo(stepNo);
        taskEntity.setProcessState(FlowEnum.ProcessState.Backed);
        entity.setProcessState(FlowEnum.ProcessState.Backed);
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.back);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(1);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }


    @Override
    public void deny(T entity, Duty duty, String comment) {
        User user = userService.getLoginInfo();
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
        Set<User> editors = new HashSet<User>();
        Set<User> readers = new HashSet<User>();
        //已办标志
        int type = 2;
        taskEntity.setProcessState(FlowEnum.ProcessState.Deny);
        entity.setProcessState(FlowEnum.ProcessState.Deny);
        List<Duty> docDutyList = Lists.newArrayList();
        if(processBrief.getDocConfig() != null){
            docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
        }
        List<Duty> editDutyList = Lists.newArrayList();
        if(processBrief.getEditConfig() != null){
            editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getEditConfig().getId());
        }
        List<Duty> readDutyList = Lists.newArrayList();
        if(processBrief.getReadConfig() != null){
            readDutyList = commonConfigService.findDutyByConfig(entity.getId(), taskEntity.getEntityName(), processBrief.getReadConfig().getId());
        }
        docDutyList.addAll(editDutyList);
        docDutyList.addAll(readDutyList);
        for(Duty readDuty: docDutyList){
            if(readDuty.getUser() != null){
                readers.add(userService.get(readDuty.getUser().getId()));
            }
        }
        for(Duty editDuty: editDutyList){
            if(editDuty.getUser() != null){
                editors.add(userService.get(editDuty.getUser().getId()));
            }
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnumManager.StateEnum.Enable);
        params.put("taskEntity", taskEntity);
        List<TaskFlow> taskFlowList1 = taskFlowService.getList(params);
        for(TaskFlow taskFlow:taskFlowList1){
            readers.add(taskFlow.getUser());
        }
        readers.add(user);
        Set<User> prevUser = Sets.newHashSet();
        prevUser.add(user);
        taskEntity.setPrevUsers(prevUser);
        taskEntity.setReaders(readers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setDuty(duty);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.deny);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        for(TaskRecord taskRecord:taskRecords){
            taskRecord.setType(2);
            taskRecordService.update(taskRecord);
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }

    @Override
    public void deny(T entity, String comment) {
        User user = userService.getLoginInfo();
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        taskEntity.setProcessState(FlowEnum.ProcessState.Deny);
        entity.setProcessState(FlowEnum.ProcessState.Deny);
        Set<User> prevUsers = Sets.newHashSet();
        taskEntity.setPrevUsers(prevUsers);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUser(user);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.deny);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), user.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        for(TaskRecord taskRecord:taskRecords){
            taskRecord.setType(2);
            taskRecordService.update(taskRecord);
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUser(user);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(2);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }

    @Override
    public SearchResultPaging paging(PagePaging page, List<Rule> rules, Order order,String entityName, FlowEnum.ProcessState[] processState, Map<String, Object> params) {
        if (rules == null){
            rules = new ArrayList<Rule>();
        }
        // 默认排序
        if (order == null){
            order = Order.order("createTime", SearchEnum.OrderType.desc);
        }
        Set<String> ids = new HashSet<String>();
        User user = userService.getLoginInfo();
        List<TaskEntity> taskEntityList = taskEntityService.getInfoByReaders(entityName, processState, user.getId());
        for(TaskEntity taskEntity:taskEntityList){
            ids.add(taskEntity.getKeyId());
        }
        if (ids.size() > 0) {
            rules.add(RuleHelper.in("id", ids));
        }else {
            return SearchResultPaging.list(Search.simpleSearchList(), 1, 1 ,Long.valueOf(1),Long.valueOf(1),new ArrayList());
        }
        return findPagingBySearch(page, rules, params, order);
    }

    @Override
    public SearchResultPaging paging(Order order, String entityName, FlowEnum.ProcessState[] processState, Map<String, Object> params) {
        List<Rule> rules = new ArrayList<Rule>();
        if (order == null){
            order = Order.order("createTime", SearchEnum.OrderType.desc);
        }
        Set<String> ids = new HashSet<String>();
        User user = userService.getLoginInfo();
        List<TaskEntity> taskEntityList = taskEntityService.getInfoByReaders(entityName, processState);
        ProcessBrief processBrief  = processBriefService.getInfoByTableKey(entityName);
        for(TaskEntity taskEntity:taskEntityList){
            if(processBrief != null && StringUtils.equals(processBrief.getShare(),"是")){
                ids.add(taskEntity.getKeyId());
            }else{
                List<TaskFlow> taskFlowList = taskFlowService.getInfoByTaskEntity(taskEntity);
                for(TaskFlow taskFlow:taskFlowList){
                    if(taskFlow.getUser() == user){
                        ids.add(taskEntity.getKeyId());
                        break;
                    }
                }
                for(User user1:taskEntity.getEditors()){
                    if(user1 == user){
                        ids.add(taskEntity.getKeyId());
                        break;
                    }
                }
            }
        }

        if (ids.size() > 0) {
            rules.add(RuleHelper.in("id", ids));
        }else {
            return SearchResultPaging.list(Search.simpleSearchList(), 1, 1 ,Long.valueOf(1),Long.valueOf(1),new ArrayList());
        }
        return findPagingBySearch(null, rules, params, order);
    }


}